package com.gloaba.logservice.service.log;

import com.gloaba.common.core.utils.DateUtils;
import com.gloaba.common.core.utils.JsonUtils;
import com.gloaba.common.core.utils.StringUtils;
import com.gloaba.common.log.constant.LogMqConstants;
import com.gloaba.logservice.entity.RequestLog;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class ApiLogListenter {

    private final IApiLogService iApiLogService;

    /**
     * 队列消息接收者
     */
    @RabbitListener(queues = LogMqConstants.LOG_API_GATWEWAY_QUEUE)
    public void messageReceiver(
            @Payload String params,
            @Headers Map<String, Object> headers,
            Channel channel
    ) {
        try {
            RequestLog requestLog = JsonUtils.parseObject(params,RequestLog.class);
            if(StringUtils.isNotEmpty(requestLog.getResponseData())){
                //解析结果
                Map<String,Object> result = JsonUtils.parseMap(requestLog.getResponseData());
                requestLog.setResultCode(MapUtils.getInteger(result,"code"));
                requestLog.setErrorMsg(MapUtils.getString(result,"message"));
            }
            RequestLog.RequestDate requestDate = new RequestLog.RequestDate();
            requestDate.setDate(DateUtils.dateTime(requestLog.getRequestTime()));
            requestDate.setYear(DateUtils.year(requestLog.getRequestTime()));
            requestDate.setYearMonth(DateUtils.monthOfYear(requestLog.getRequestTime()));
            requestDate.setMonth(StringUtils.padl(requestLog.getRequestTime().getMonth(),2));
            requestDate.setDay(StringUtils.padl(requestLog.getRequestTime().getDay(),2));
            requestDate.setHour(StringUtils.padl(requestLog.getRequestTime().getHours(),2));
            requestDate.setMinute(StringUtils.padl(requestLog.getRequestTime().getMinutes(),2));
            requestLog.setRequestDate(requestDate);
            String collectionName = String.format("RequestLog_%s",DateUtils.parseDateToStr("yyyyMMdd",requestLog.getRequestTime()));
            iApiLogService.saveEntity(requestLog,collectionName);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
    }
}
